package com.qf.j2112.service.impl;

import com.qf.j2112.mapper.CartMapper;
import com.qf.j2112.po.Cart;
import com.qf.j2112.service.CartService;
import com.qf.j2112.vo.ClientCartVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Resource
    private CartMapper cartMapper;

    @Override
    public List<Cart> getOnesCart(int uid) {
        return cartMapper.getOnesCart(uid);
    }

    @Transactional //开启事务
    @Override
    public boolean addToCart(ClientCartVo cart) {

//        判断商品是否存在与数据库
        Cart cart1 = cartMapper.findOneByUidAid(cart.getUid(), cart.getGoodId());
        if(ObjectUtils.isEmpty(cart1)){
            int i = cartMapper.addToCart(cart);
            if (i>-1) {
                return true;
            }
        }else{
            //原来的数量+1
            Integer newNum=cart1.getNum()+cart.getCartCount();
            cart1.setNum(newNum);
            cartMapper.updateOnesCart(cart1);

        }
            return false;
    }

    @Override
    public boolean updateOnesCart(Cart cart) {
        Cart cart1=cartMapper.findOneByCid(cart.getCartId());
        cart1.setNum(cart.getNum());
        cart1.setTotalMoney(cart.getNum()*cart1.getAreaPrice());
        cart1.setCreateTime(new Date());
        int i= cartMapper.updateOnesCart(cart1);
        if(i>-1){
            return true;
        }
        return false ;
    }

    @Override
    public Cart findOneByUidAid(int uid, int aid) {
        return cartMapper.findOneByUidAid(uid,aid);
    }

    @Override
    public boolean deleteCart(int cid) {
        int i= cartMapper.deleteCart(cid);
        if(i>-1){
            return true;
        }
        return false ;
    }

    @Override
    public boolean clearOnesCart(int uid) {
        int i= cartMapper.clearOnesCart(uid);
        if(i>-1){
            return true;
        }
        return false ;
    }
}
